package com.library.filter;

import com.library.entity.Reader;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 对图书页面进行过滤，如果未登陆，则跳转到登陆页面
 */
@WebFilter("/book")
public class ReaderFilter implements Filter {

    /**
     * 过滤器方法体
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断此前是否是登陆状态
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpSession session = request.getSession();
        Reader reader = (Reader) session.getAttribute("reader");
        //如果读者为空，则转到登陆页面
        //如果读者不为空，则请求继续向后传递
        if(reader==null){
            ((HttpServletResponse)servletResponse).sendRedirect("login.jsp");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
}
